package com.khotyn.heresy.service;

import java.util.List;

import com.khotyn.heresy.bean.PictureDetail;
import com.khotyn.heresy.bean.Tag;
import com.khotyn.heresy.dao.PictureDAO;
import com.khotyn.heresy.dao.TagDAO;
import com.khotyn.heresy.util.ListOperation;

public class PictureEditService {
	private PictureDAO pictureDAO;
	private TagDAO tagDAO;

	/**
	 * 服务类，处理编辑图片属性的请求
	 * 
	 * @param picture 图片Bean
	 * @param tagString 标签String
	 * @param requestUrl 请求的页面URL
	 */
	@SuppressWarnings("unchecked")
	public void doService(PictureDetail picture, List<String> tags, String requestUrl) {
		// 标签处理
		List<String> tagDelete = ListOperation.minus(picture.getPictureTags(), tags); // 需要被删除的标签
		List<String> tagNew = ListOperation.minus(tags, picture.getPictureTags()); // 需要新加入的标签

		doDBOperate(picture, tagDelete, tagNew);
	}

	/**
	 * 相册编辑数据库操作
	 * 
	 * @param picture
	 * @param requestUrl
	 * @param tagDelete
	 * @param tagNew
	 */
	public void doDBOperate(PictureDetail picture, List<String> tagDelete, List<String> tagNew) {

		pictureDAO.updatePictureByID(picture);

		for (String str : tagDelete) {
			tagDAO.deletePictureTag(picture.getPictureID(), tagDAO.selectTagByName(str).getTagID());
		}

		for (String str : tagNew) {
			Tag tag = tagDAO.selectTagByName(str);

			if (tag == null) {
				tag = new Tag();

				if (str != null && !str.trim().equals("")) {
					tag.setTagName(str);
					tagDAO.insertTag(tag);
					tag = tagDAO.selectTagByName(str);
					System.out.println(tag.getTagID());
					tagDAO.insertPictureTag(picture.getPictureID(), tag.getTagID());
				}
			}
		}

		picture.setPictureTags(tagDAO.selectTagByPictureID(picture.getPictureID()));
	}

	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}

	public void setTagDAO(TagDAO tagDAO) {
		this.tagDAO = tagDAO;
	}

	public PictureDAO getPictureDAO() {
		// TODO Auto-generated method stub
		return this.pictureDAO;
	}
}
